import PageLayout from "@/components/PageLayout";
import {
  Blockquote,
  Box,
  Button,
  Center,
  Flex,
  Group,
  Pagination,
  Select,
  Table,
  Text,
  Textarea,
} from "@mantine/core";
import dayjs from "dayjs";

import { useAPIUtils } from "@/components/APIUtilsProvider";
import EmptyListPlaceholder from "@/components/EmptyListPlaceHolder";
import When from "@/components/When";
import { DateTimePicker } from "@mantine/dates";
import { useForm } from "@mantine/form";
import { modals } from "@mantine/modals";
import { IconSearch } from "@tabler/icons-react";
import { useImmer } from "use-immer";

import { useParams } from "react-router-dom";
import ProductPill from "../../components/ProductPill";
import UserPill from "../../components/UserPill";

export default function JoyMessageList() {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const { channel } = useParams();

  const [pagingCondition, setPagingCondition] = useImmer({
    replied: "",
    start: dayjs().subtract(7, "days").toDate(),
    end: new Date(),
    pageIndex: 0,
    pageSize: 10,
  });

  const searchForm = useForm({
    mode: "uncontrolled",
    initialValues: {
      start: dayjs().subtract(7, "days").toDate(),
      end: new Date(),
      replied: "",
    },
    validate: {},
  });

  const search = (values) => {
    tanstackInvalidate(`/api/admin/joyMessages/${channel}`);
    setPagingCondition({
      ...values,
      pageSize: pagingCondition.pageSize,
      pageIndex: 0,
    });
  };

  const makeReply = async (id, values) => {
    await restPUT(`/api/admin/joyMessages/${channel}/${id}`, values);
    tanstackInvalidate(`/api/admin/joyMessages/${channel}`);
    tanstackInvalidate(`/api/joyMessages/${id}`);
  };

  const joyMessageQuery = tanstackQuery(`/api/admin/joyMessages/${channel}`, {
    ...pagingCondition,
    replied: pagingCondition.replied || "",
    start: dayjs(pagingCondition.start).format("YYYY-MM-DDTHH:mm:ss"),
    end: dayjs(pagingCondition.end).format("YYYY-MM-DDTHH:mm:ss"),
    pageNo: pagingCondition.pageIndex,
    pageSize: pagingCondition.pageSize,
  });

  const totalPages = joyMessageQuery.data?.totalPages;
  const rows = joyMessageQuery.data?.content.map((joyMessage, index) => (
    <Table.Tr key={index}>
      <Table.Td>
        <Text>{index + 1}</Text>
      </Table.Td>
      {channel === "productConsult" && (
        <Table.Td>
          <ProductPill productId={joyMessage.subChannel} />
        </Table.Td>
      )}
      <Table.Td>
        <Box w={"300"}>
          <Text truncate="end">{joyMessage.content}</Text>
        </Box>
      </Table.Td>
      <Table.Td>
        <UserPill user={joyMessage.client} />
      </Table.Td>
      <Table.Td>
        {dayjs(joyMessage.createdAt).format("YYYY/MM/DD HH:mm")}
      </Table.Td>
      <Table.Td c={joyMessage.replied ? "green.6" : "red.6"}>
        {joyMessage.replied ? "已答复" : "待答复"}
      </Table.Td>
      <Table.Td>
        <Group>
          <Button
            size="xs"
            onClick={() =>
              openQuickReplyModal({
                data: joyMessage,
                onConfirm: makeReply,
              })
            }
            disabled={joyMessage.replied}
          >
            快速答复
          </Button>
          <Button
            variant="subtle"
            size="xs"
            onClick={() => window.open(`./${joyMessage.id}/details`, "_blank")}
          >
            详情
          </Button>
        </Group>
      </Table.Td>
    </Table.Tr>
  ));

  return (
    <PageLayout title={channel === "productConsult" ? "商品咨询" : "健康咨询"}>
      <form onSubmit={searchForm.onSubmit(search)}>
        <Flex
          mih={50}
          mb={44}
          gap="md"
          justify="flex-end"
          align="flex-end"
          direction="row"
          wrap="wrap"
        >
          <DateTimePicker
            description="时间开始"
            {...searchForm.getInputProps("start")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <DateTimePicker
            description="时间结束"
            {...searchForm.getInputProps("end")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />

          <Select
            clearable
            placeholder="默认全部"
            label="答复情况"
            {...searchForm.getInputProps("replied")}
            data={[
              { label: "已答复", value: "true" },
              { label: "未答复", value: "false" },
            ]}
          />

          <Button type="submit" rightSection={<IconSearch size={14} />}>
            搜索
          </Button>
        </Flex>
      </form>

      <When condition={rows?.length > 0}>
        <Table verticalSpacing={"sm"}>
          <Table.Thead>
            <Table.Tr>
              <Table.Th w={"3%"}></Table.Th>
              {channel === "productConsult" && (
                <Table.Th w={"10%"}>品名</Table.Th>
              )}
              <Table.Th w={"40%"}>内容</Table.Th>
              <Table.Th w={"10%"}>提问人</Table.Th>
              <Table.Th w={"10%"}>时间</Table.Th>
              <Table.Th w={"15%"}>状态</Table.Th>
              <Table.Th>操作</Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>{rows}</Table.Tbody>
        </Table>
        <Center mt={40}>
          <Pagination
            total={totalPages}
            value={pagingCondition.pageIndex + 1}
            onChange={(e) => {
              setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
            }}
          />
        </Center>
      </When>
      <When condition={rows?.length == 0}>
        <EmptyListPlaceholder />
      </When>
    </PageLayout>
  );
}

function openQuickReplyModal(props) {
  modals.open({
    title: "快速答复",
    size: "60%",
    centered: true,
    children: <QuickReplyForm onConfirm={props.onConfirm} data={props.data} />,
    labels: { confirm: "确定", cancel: "取消" },
  });
}

function QuickReplyForm({ onConfirm, data }) {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const form = useForm({
    initialValues: {
      reply: "",
    },

    validate: {},
  });

  return (
    <Box w="96%" mx="auto">
      <form
        onSubmit={form.onSubmit((values) => {
          onConfirm(data.id, values);
          modals.closeAll();
        })}
      >
        <Blockquote>{data.content}</Blockquote>

        <Textarea
          withAsterisk
          label="请填写答复"
          autosize
          maxRows={8}
          minRows={4}
          {...form.getInputProps("reply")}
        />

        <Group justify="flex-end" mt="md">
          <Button type="submit">Submit</Button>
        </Group>
      </form>
    </Box>
  );
}
